package com.whfc.emp.helmet;

import com.alibaba.fastjson.JSONObject;
import com.whfc.common.exception.BizException;
import com.whfc.common.third.helmet.HelmetProperties;
import com.whfc.common.util.HttpUtil;
import com.whfc.emp.param.AppHelmetTestParam;
import com.whfc.emp.redis.ZbznTokenRedisDao;
import com.whfc.emp.websocket.ZbznWebSocketClient;
import org.java_websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Component
public class ZbznVideoApi {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    // 筑邦智能安全帽操作
    private  static final String user_name = "bruce";

//    private  static final String pwd = "Admin!@#16891";
    private  static final String pwd = "Admin!@%2316891";


    // http路径
    private  static final String basehttpUrl = "https://111.120.11.161:10006/api";

    // 获取key
    private  static final String get_pkey = "/index.php?ctl=tool&act=get_pkey";

    // 获取token
    private  static final String get_token = "/index.php?ctl=tool&act=get_token";

    //-----------------websocket 指令----------------------------------
    // (发---收)
    public   static final String cmd_login = "ma_login";
    // 实时设备数据(发---收)
    public  static final String cmd_active_devices = "ma_get_active_devices";
    // 接收报警推送(收)
    public  static final String cmd_push_sos = "server_push_sos";
    //------------------------------------------------------------------

//    @Lazy
    @Resource(name = "zbznWebSocket")
    private WebSocketClient zbznWebSocket;

    @Autowired
    private ZbznTokenRedisDao zbznTokenRedisDao;

    @Autowired
    private HelmetProperties helmetProperties;

    /**
     * 获取token
     * @return
     */
    public  String getToken(){
        String token = zbznTokenRedisDao.get(user_name);
        logger.info("获取redis token：{}", token);
        if (StringUtils.hasText(token)) {
            return token;
        }
        // 获取key
        String getKeyUrl = String.format("&user_name=%s&pwd=%s", user_name, pwd);
        StringBuilder stringBuilder = new StringBuilder();
        String keyUrl = stringBuilder.append(basehttpUrl).append(get_pkey).append(getKeyUrl).toString();
        String keyResult = HttpUtil.doPost(keyUrl,"");
        // 获取token
        JSONObject keyJson = JSONObject.parseObject(keyResult);
        if (!"success".equals(keyJson.getString("msg"))) {
            throw new BizException("500","视频安全帽获取key失败");
        }
        String getTokenUrl = String.format("&user_name=%s&pkey=%s", user_name, keyJson.getString("data"));
        StringBuilder tokenUrlBuilder = new StringBuilder();
        String tokenUrl = tokenUrlBuilder.append(basehttpUrl).append(get_token).append(getTokenUrl).toString();
        String tokenResult = HttpUtil.doPost(tokenUrl,"");
        JSONObject tokenObject = JSONObject.parseObject(tokenResult);
        if (!"GetSucc".equals(tokenObject.getString("msg_code"))) {
            throw new BizException("500","获取token失败");
        }
        token = tokenObject.getString("token");
        zbznTokenRedisDao.set(user_name,token);
        return token;
    }

    /**
     * 模拟数据
     * @param mockData
     */
    public void sendMock(String mockData){
        JSONObject jsonObject = JSONObject.parseObject(mockData);
        long currentTime = System.currentTimeMillis() / 1000;
        String c_time = jsonObject.getString("c_time");
        logger.info("模拟数据 c_time：{}", c_time);
        jsonObject.put("c_time", currentTime);
        c_time = jsonObject.getString("c_time");
        logger.info("模拟数据替换 c_time：{}", c_time);
        jsonObject.put("time", currentTime);
        if (zbznWebSocket instanceof ZbznWebSocketClient) {
            ((ZbznWebSocketClient) zbznWebSocket).sendMockMsg(jsonObject.toJSONString());
        }
    }

    public  void sendMockMsg(String type){
        JSONObject jsonObject = null;
        long currentTime = System.currentTimeMillis() / 1000;
        switch ( type){
            case "server_push_sos":
                jsonObject = JSONObject.parseObject(ZbznVideoParse.mock_data_push_sos);
                jsonObject.put("c_time", currentTime);
                jsonObject.put("time", currentTime);
                break;
            case "ma_get_active_devices":
                jsonObject = JSONObject.parseObject(ZbznVideoParse.mock_data_get_active_devices);
                jsonObject.put("c_time", currentTime);
                break;
            case "ma_login":
                this.login();
                return;
            default:
                jsonObject = JSONObject.parseObject(ZbznVideoParse.mock_data_get_active_devices);
                jsonObject.put("c_time", currentTime);
                break;
        }

        if (zbznWebSocket instanceof ZbznWebSocketClient) {
            ((ZbznWebSocketClient) zbznWebSocket).sendMockMsg(jsonObject.toJSONString());
        }
    }

    /**
     * 登录
     */
    public  void login(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("act",cmd_login);
        jsonObject.put("user_name",user_name);
        jsonObject.put("access_token",getToken());
        if (zbznWebSocket instanceof ZbznWebSocketClient) {
            ((ZbznWebSocketClient) zbznWebSocket).sendMsg(jsonObject.toJSONString());
        } else {
            zbznWebSocket.send(jsonObject.toJSONString());
        }
    }

    /**
     * 发送获取设备信息
     */
    public  void getDeviceInfo(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("act",cmd_active_devices);
        if (zbznWebSocket instanceof ZbznWebSocketClient) {
            ((ZbznWebSocketClient) zbznWebSocket).sendMsg(jsonObject.toJSONString());
        } else {
            zbznWebSocket.send(jsonObject.toJSONString());
        }
    }
}